<?php

namespace App;

use Illuminate\Database\Eloquent\Builder;
use Laravel\Scout\Searchable;

class Post extends Model
{
    use Searchable;

    public function searchableAs()
    {
        return 'post';
    }

    public function toSearchableArray()
    {
        return [
            'title'=>$this->title,
            'content'=>$this->content,
        ];
    }

    public function user(){
        return $this->belongsTo('App\User', 'user_id', 'id');
    }

    public function comments(){
        return $this->hasMany('App\Comment')->orderBy('created_at', 'desc');
    }

    // 关联
    public function zan($user_id){
        return $this->hasOne(Zan::class)->where('user_id', $user_id);
    }
    // 文章的所有攒
    public function zans(){
        return $this->hasMany(Zan::class);
    }

    protected static function boot(){
        parent::boot();
        static::addGlobalScope('avaiable', function (Builder $builder){
            $builder->whereIn('status', [0,1]);
        });
    }
}
